//
//  SkyAssociationMenuView.m
//
//  Created by skytoup on 14-10-24.
//  Copyright (c) 2014年 skytoup. All rights reserved.
//

#import "SkyAssociationMenuView.h"

NSString *const IDENTIFIER = @"CELL";

@interface SkyAssociationMenuView () <UITableViewDataSource, UITableViewDelegate, UIGestureRecognizerDelegate>
{
    NSArray *tables;

}
@property(nonatomic,strong)UIView *baView;
@property(nonatomic,assign)NSInteger  index;
@end

@implementation SkyAssociationMenuView

- (instancetype)initWithFrame:(CGRect)frame lastClassTitle:(NSString *)title;
{
    self = [super initWithFrame:frame];
    if (self) {
        // 初始化选择项
        for(int i=0; i!=3; ++i) {
            sels[i] = -1;
        }
        _index = 0;
        self.frame = frame;
        self.userInteractionEnabled = YES;
        UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        cancelBtn.frame = CGRectMake(CGRectGetWidth(self.frame)/2,0 , CGRectGetWidth(self.frame)/2,  30);
        cancelBtn.titleLabel.font =[UIFont systemFontOfSize:13*VerticalTexeRatio()];
           cancelBtn.backgroundColor = [UIColor colorWithWhite:0.831 alpha:1.000];
        [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [cancelBtn addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:cancelBtn];
  
        
        UIButton *cancelBttn = [UIButton buttonWithType:UIButtonTypeCustom];
        cancelBttn.frame = flexibleFrame(CGRectMake(0, 0, CGRectGetWidth(self.frame)/2, 30), NO);
        cancelBttn.backgroundColor = [UIColor colorWithRed:0.075 green:0.231 blue:0.455 alpha:1.000];
        cancelBttn.titleLabel.font =[UIFont systemFontOfSize:13*VerticalTexeRatio()];
        [cancelBttn setTitle:title forState:UIControlStateNormal];
        [cancelBttn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [cancelBttn addTarget:self action:@selector(changeIndex) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:cancelBttn];
    }
    return self;
}

#pragma mark private
/**
 *  调整表视图的位置、大小
 */
- (void)adjustTableViews{
//    int w = SCREEN_WIDTH;
//    int __block showTableCount = 0;
//    [tables enumerateObjectsUsingBlock:^(UITableView *t, NSUInteger idx, BOOL *stop) {
//        CGRect rect = t.frame;
//        rect.size.height = SCREEN_HEIGHT - bgView.frame.origin.y;
//        t.frame = rect;
//        if(t.superview)
//            ++showTableCount;
//    }];
//    
//    for(int i=0; i!=showTableCount; ++i){
//        UITableView *t = [tables objectAtIndex:i];
//        CGRect f = t.frame;
//        f.size.width = w / showTableCount;
//        f.origin.x = f.size.width * i;
//        t.frame = f;
//    }
    
    UITableView *t = [tables objectAtIndex:_index];
 
    [UIView animateWithDuration:0.3 animations:^{
        
         t.frame = CGRectMake(0, 0, CGRectGetWidth(_baView.frame), CGRectGetHeight(_baView.frame));
        if (_index>0) {
            UITableView * lastT = [tables objectAtIndex:_index-1];
            lastT.frame = CGRectMake(0, 0, 0, CGRectGetHeight(_baView.frame));
        }
        
    }];
   
    
}
/**
 *  取消选择
 */
- (void)cancel{
    [self dismiss];
    if([self.delegate respondsToSelector:@selector(assciationMenuViewCancel)]) {
        [self.delegate assciationMenuViewCancel];
    }
}

- (void)changeIndex{
    if (_index!= 0) {
        _index--;
    }else{
        _index = 0  ;
    }
    UITableView *t = [tables objectAtIndex:_index];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        t.frame =  t.frame = CGRectMake(0, 0, CGRectGetWidth(_baView.frame), CGRectGetHeight(_baView.frame));;
        if (_index<2) {
            UITableView * lastT = [tables objectAtIndex:_index+1];
            lastT.frame = CGRectMake(CGRectGetWidth(_baView.frame), 0, 0, CGRectGetHeight(_baView.frame));
        }
        
    }];
}

/**
 *  保存table选中项
 */
- (void)saveSels{
    [tables enumerateObjectsUsingBlock:^(UITableView *t, NSUInteger idx, BOOL *stop) {
        sels[idx] = t.superview ? t.indexPathForSelectedRow.row : -1;
    }];
}

/**
 *  加载保存的选中项
 */
- (void)loadSels{
    [tables enumerateObjectsUsingBlock:^(UITableView *t, NSUInteger i, BOOL *stop) {
        [t selectRowAtIndexPath:[NSIndexPath indexPathForRow:sels[i] inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
        if((sels[i] != -1 && !t.superview) || !i) {
            [_baView addSubview:t];
        }
    }];
}

#pragma mark public
- (void)setSelectIndexForClass1:(NSInteger)idx_1 class2:(NSInteger)idx_2 class3:(NSInteger)idx_3 {
    sels[0] = idx_1;
    sels[1] = idx_2;
    sels[2] = idx_3;
}

- (void)showAsDrawDownView{
//    CGRect showFrame = view.frame;
//    CGFloat x = 0.f;
//    CGFloat y = showFrame.origin.y+showFrame.size.height;
//    CGFloat w = SCREEN_WIDTH;
//    CGFloat h = SCREEN_HEIGHT-y;
  
    
    if(!_baView.superview) {
        // 初始化菜单
        tables = @[[[UITableView alloc] init], [[UITableView alloc] init], [[UITableView alloc] init] ];
        [tables enumerateObjectsUsingBlock:^(UITableView *table, NSUInteger idx, BOOL *stop) {
            [table registerClass:[UITableViewCell class] forCellReuseIdentifier:IDENTIFIER ];
            table.dataSource = self;
            table.delegate = self;
//            table.frame = CGRectMake(0, 0,CGRectGetWidth(_baView.frame), CGRectGetHeight(_baView.frame) );
            table.backgroundColor = [UIColor clearColor];
            table.tableFooterView = [UIView new];
        }];

        
        _baView = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 30,CGRectGetWidth(self.frame), CGRectGetHeight(self.frame)-30), NO)];
        _baView.userInteractionEnabled = YES;
        _baView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_baView];
    }
    [_baView addSubview:[tables objectAtIndex:0]];
    [self loadSels];
    [self adjustTableViews];
    if(!self.superview) {
        [[[UIApplication sharedApplication] keyWindow] addSubview:self];
        self.alpha = .0f;
        [UIView animateWithDuration:.25f animations:^{
            self.alpha = 1.0f;
        }];
    }
    [[[UIApplication sharedApplication] keyWindow] bringSubviewToFront:self];
}

- (void)dismiss{
    if(self.superview) {
        [UIView animateWithDuration:.25f animations:^{
            self.alpha = .0f;
        } completion:^(BOOL finished) {
            [_baView.subviews enumerateObjectsUsingBlock:^(UIView *obj, NSUInteger idx, BOOL *stop) {
                [obj removeFromSuperview];
            }];
            [_baView removeFromSuperview];
            [self removeFromSuperview];
        }];
    }
}

#pragma mark UITableViewDateSourceDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:IDENTIFIER];
    if(tableView == [tables objectAtIndex:0]){
        cell.textLabel.text = [_delegate assciationMenuView:self titleForClass_1:indexPath.row];
    }else if(tableView == [tables objectAtIndex:1]){
        cell.textLabel.text = [_delegate assciationMenuView:self titleForClass_1:((UITableView*)tables[0]).indexPathForSelectedRow.row class_2:indexPath.row];
    }else if(tableView == [tables objectAtIndex:2]){
        cell.textLabel.text = [_delegate assciationMenuView:self titleForClass_1:((UITableView*)tables[0]).indexPathForSelectedRow.row class_2:((UITableView*)tables[1]).indexPathForSelectedRow.row class_3:indexPath.row];
    }
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger __block count;
    [tables enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if(obj == tableView) {
            count = [_delegate assciationMenuView:self countForClass:idx];
            *stop = YES;
        }
    }];
    return count;
}

#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableView *t0 = [tables objectAtIndex:0];
    UITableView *t1 = [tables objectAtIndex:1];
    UITableView *t2 = [tables objectAtIndex:2];
    BOOL isNexClass = true;
    if(tableView == t0){
        _index = 1 ;
        if([self.delegate respondsToSelector:@selector(assciationMenuView:idxChooseInClass1:)]) {
            isNexClass = [_delegate assciationMenuView:self idxChooseInClass1:indexPath.row];
        }
        if(isNexClass) {
            [t1 reloadData];
            if(!t1.superview) {
                [_baView addSubview:t1];
            }
            if(t2.superview) {
                [t2 removeFromSuperview];
            }
            [self adjustTableViews];
        }else{
            if(t1.superview) {
                [t1 removeFromSuperview];
            }
            if(t2.superview) {
                [t2 removeFromSuperview];
            }
            [self saveSels];
            [self dismiss];
        }
    }else if(tableView == t1) {
        _index = 2;
        if([self.delegate respondsToSelector:@selector(assciationMenuView:idxChooseInClass1:class2:)]) {
            isNexClass = [_delegate assciationMenuView:self idxChooseInClass1:t0.indexPathForSelectedRow.row class2:indexPath.row];
        }
        if(isNexClass){
            
            [t2 reloadData];
            if(!t2.superview) {

                [_baView addSubview:t2];
              
            }
            
            [self adjustTableViews];
        }else{
            if(t2.superview) {
                [t2 removeFromSuperview];
            }
            [self saveSels];
            [self dismiss];
        }
    }else if(tableView == t2) {
        _index = 2;
        if([self.delegate respondsToSelector:@selector(assciationMenuView:idxChooseInClass1:class2:class3:)]) {
            isNexClass = [_delegate assciationMenuView:self idxChooseInClass1:t0.indexPathForSelectedRow.row class2:t1.indexPathForSelectedRow.row class3:indexPath.row];
        }
        if(isNexClass) {
          
            [self saveSels];
            [self dismiss];
        }
    }
}

@end
